package com.example.demo.service;

import com.aliyun.auth.credentials.Credential;
import com.aliyun.auth.credentials.provider.StaticCredentialProvider;
import com.aliyun.sdk.service.dysmsapi20170525.*;
import com.aliyun.sdk.service.dysmsapi20170525.models.*;
import com.example.demo.config.AlibabaCloudConfig;
import com.example.demo.model.dto.SendSmsRequestDTO;
import com.google.gson.Gson;

import darabonba.core.client.ClientOverrideConfiguration;
import org.springframework.stereotype.Service;

import java.util.concurrent.CompletableFuture;

/**
 * 短信服务。
 *  此服务使用阿里云短信服务API发送短信。
 */
@Service("customSmsService") // 指定服务名称
public class SmsService {

    private final AlibabaCloudConfig alibabaCloudConfig;

    /**
     * 构造函数，依赖注入阿里云配置。
     * @param alibabaCloudConfig 阿里云配置对象
     */
    public SmsService(AlibabaCloudConfig alibabaCloudConfig) {
        this.alibabaCloudConfig = alibabaCloudConfig;
    }

    /**
     * 发送短信。
     * @param requestDTO 发送短信请求DTO
     * @return 阿里云短信服务API返回的JSON字符串
     * @throws Exception 异常
     */
    public String sendSms(SendSmsRequestDTO requestDTO) throws Exception {
        try (AsyncClient client = createClient()) { // 使用try-with-resources自动关闭客户端
            SendSmsRequest sendSmsRequest = SendSmsRequest.builder()
                    .phoneNumbers(requestDTO.getPhoneNumbers())
                    .templateCode(requestDTO.getTemplateCode())
                    .templateParam(requestDTO.getTemplateParam())
                    .signName(requestDTO.getSignName())
                    .build();

            CompletableFuture<SendSmsResponse> response = client.sendSms(sendSmsRequest); // 异步发送短信
            SendSmsResponse resp = response.get(); // 获取结果

            return new Gson().toJson(resp); // 将结果转换为JSON字符串
        }
    }

    /**
     * 创建阿里云短信服务客户端。
     * @return 阿里云短信服务异步客户端
     */
    private AsyncClient createClient() {
        StaticCredentialProvider provider = StaticCredentialProvider.create(Credential.builder()
                .accessKeyId(alibabaCloudConfig.getAccessKeyId())
                .accessKeySecret(alibabaCloudConfig.getAccessKeySecret())
                .build());

        return AsyncClient.builder()
                .region("cn-shenzhen") // 阿里云区域
                .credentialsProvider(provider) // 凭证提供者
                .overrideConfiguration(
                        ClientOverrideConfiguration.create()
                                .setEndpointOverride("dysmsapi.aliyuncs.com") // 阿里云短信服务API端点
                )
                .build();
    }
}